import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {

    // 从URL下载图片并保存到指定路径
    public static void saveImage(String url, String savePath) throws IOException {
        URL imageUrl = new URL(url);
        try (InputStream in = imageUrl.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }

    // 检查目录是否存在，不存在则创建
    public static void ensureDirectoryExists(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    // 将下载信息追加到日志文件
    public static void appendLog(String url, String savePath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        String log = String.format("[%s] Downloaded: %s -> %s%n", time, url, savePath);

        try (BufferedWriter writer = new BufferedWriter(new FileWriter("download_log.txt", true))) {
            writer.write(log);
        } catch (IOException e) {
            System.out.println("日志写入失败: " + e.getMessage());
        }
    }

}
